#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Download a specific logo with correct URL path
"""

import os
import requests

# 配置
BASE_DOMAIN = "https://www.shanghairanking.cn/"
LOGO_DIR = "logos"
HEADERS = {
    "User-Agent": "Mozilla/5.0 (compatible; DataCollector/1.0; +https://example.com)"
}

os.makedirs(LOGO_DIR, exist_ok=True)

def download_logo_with_correct_path(logo_filename, rank="", slug=""):
    """
    使用正确的路径下载logo图片
    
    Args:
        logo_filename: logo文件名，例如 "6432819300.jpg"
        rank: 排名（可选，用于文件命名）
        slug: 大学标识（可选，用于文件命名）
    """
    # 构造正确的URL路径
    correct_url = f"{BASE_DOMAIN}_uni/logo-jpg/{logo_filename}"
    
    # 生成输出文件名
    ext = os.path.splitext(logo_filename)[1] or ".jpg"
    safe_slug = slug or "university"
    safe_slug = "".join(c if c.isalnum() or c in "-_" else "_" for c in safe_slug)[:80]
    
    if rank:
        outfn = os.path.join(LOGO_DIR, f"{str(rank).zfill(2)}_{safe_slug}{ext}")
    else:
        outfn = os.path.join(LOGO_DIR, f"{safe_slug}{ext}")
    
    # 下载文件
    try:
        print(f"正在下载: {correct_url}")
        r = requests.get(correct_url, headers=HEADERS, timeout=30, stream=True)
        if r.status_code == 200:
            with open(outfn, "wb") as f:
                for chunk in r.iter_content(1024):
                    f.write(chunk)
            print(f"成功下载到: {outfn}")
            return True
        else:
            print(f"下载失败，HTTP状态码: {r.status_code}")
            return False
    except Exception as e:
        print(f"下载异常: {e}")
        return False

def main():
    # 下载特定的logo文件
    logo_filename = "6432819300.jpg"
    print(f"开始下载 {logo_filename}")
    download_logo_with_correct_path(logo_filename, rank="46", slug="specific_university")

if __name__ == "__main__":
    main()